package com.zuiacsn.forum.service.impl;

import com.zuiacsn.forum.common.AppResult;
import com.zuiacsn.forum.common.ResultCode;
import com.zuiacsn.forum.dao.ArticleReplyMapper;
import com.zuiacsn.forum.exception.ApplicationException;
import com.zuiacsn.forum.model.ArticleReply;
import com.zuiacsn.forum.service.IArticleReplayService;
import com.zuiacsn.forum.service.IArticleService;
import com.zuiacsn.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleReplyServiceImpl implements IArticleReplayService {

    @Autowired
    private ArticleReplyMapper articleReplyMapper;
    @Autowired
    IArticleService articleService;
    /**
     * 新增帖子回复
     * @param articleReply
     */
    public void create(ArticleReply articleReply) {
        // 非空检验
        if(articleReply == null || articleReply.getArticleId() == null ||
           articleReply.getPostUserId()==null || StringUtil.isEmpty(articleReply.getContent())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 设置默认值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        articleReply.setCreateTime(new Date());
        articleReply.setUpdateTime(new Date());
        // 更新数据库
        int row = articleReplyMapper.insertSelective(articleReply);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        //更新帖子表中的回复数
        articleService.addOneReplayCountById(articleReply.getArticleId());
        log.info("回复成功 ! article id = "+articleReply.getArticleId()+", user id = "+articleReply.getPostUserId());
    }

    /**
     * 根据帖子id查询回复列表
     * @param articleId
     * @return
     */
    public List<ArticleReply> selectByArticleId(Long articleId) {
        // 非空校验
        if(articleId == null || articleId <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        List<ArticleReply> articleReplies = articleReplyMapper.selectByArticleId(articleId);
        return articleReplies;
    }

}
